const appConfig = require('../config')

var bkAuth = {
  requestWithCredentials: function(obj) {
    if(!obj.hasOwnProperty('header')){
      obj.header = {}
    }

    obj.header.bktoken = this.globalData.bktoken // 添加bktoken用于身份认证
    wx.request(obj) // 调用微信request
  },
  updateBkUserInfo: function (encryptedData, iv, callback) {
    this.requestWithCredentials({
      url: appConfig.APP_URL_PREFIX + 'login/update_userinfo/',
      method: 'POST',
      data:{
        encryptedData: encryptedData,
        iv: iv
      },
      success: function (res) {
        var resData = res.data
        if(resData.code == 200) {
          console.log('后端更新用户信息成功')
          callback && callback()
        }
      }
    })
  },
  setUserInfo: function (userInfo, encryptedData, iv, callback) {
    this.globalData.userInfo = userInfo
    this.updateBkUserInfo(encryptedData, iv, callback)
  },
  // 尝试更新用户信息,并设置全局变量userinfo
  trySetUserInfo: function () {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setUserInfo(res.userInfo, res.encryptedData, res.iv)
            }
          })
        }
      }
    })
  },
  bkLogin: function (code) {
    wx.request({
      url: appConfig.APP_URL_PREFIX + 'login/',
      method: 'POST',
      data: {code: code},
      success: (res) => {
        var resData = res.data
        // 登录成功
        if(resData.code == 200){
          var bktoken = resData.data.bktoken
          // storage设置bktoken
          wx.setStorage({
            key: 'bktoken',
            data: bktoken
          })
          this.globalData.bktoken = bktoken // 设置全局变量bktoken
          this.trySetUserInfo() // 尝试更新用户信息
        }
      }
    })
  },
  login: function () {
    wx.login({
      success: res => {
        this.bkLogin(res.code)
      },
    })
  },
  initBkAuth: function () {
  	// 检查bktoken是否存在
    var bktoken = wx.getStorageSync('bktoken')
    console.log(this.globalData)
    if(!bktoken){
      this.login()
    }else{
      // bktoken以微信session_key为有效期，检查session是否有效
      wx.checkSession({
        fail: () => {
          // session_key 已经失效，需要重新执行登录流程
          this.login() //重新登录
        },
        success: () => {
          this.globalData.bktoken = bktoken // 设置全局变量bktoken
          this.trySetUserInfo() // 尝试更新用户信息
        }
      })
    }
	},
  globalData: {
    userInfo: null,
    bktoken: null
  }
}

module.exports = bkAuth
